using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using Onenote = Microsoft.Office.Interop.OneNote;

namespace cwebber
{
    class Program
    {
        static void Main(string[] args)
        {
            Onenote.Application oneApp;
            XmlNodeList xnlNotebooks;
            Logger logger = new Logger();

            #region Initialization
            
            // Obtain reference to OneNOte
            try { oneApp = new Onenote.Application(); }
            catch (Exception e)
            {
                Console.WriteLine("Error: Could not obtain reference to OneNote (" + e.Message + ")");
                return;
            }

            // Obtain list of notebooks
            xnlNotebooks = Webber.ONXmlRequestor.GetNodes(oneApp, null, Onenote.HierarchyScope.hsNotebooks, "//one:Notebook");
            if (xnlNotebooks == null)
            {
                Console.WriteLine("Error: Could not obtain list of notebooks");
                return;
            } 
            #endregion

            #region Zero Args - List Notebooks
            if (args.Length == 0)
            {
                foreach (XmlNode n in xnlNotebooks)
                {
                    Console.WriteLine(n.Attributes["name"].Value);
                }
                Console.WriteLine();
                Console.WriteLine("To export a notebook type: cwebber <notebook> <export path> [log file]");
                Console.WriteLine("For additional information: cwebber /?");
                // TODO: Add extra details on how to use it
            } 
            #endregion

            #region One Arg - Display Info
            else if (args.Length == 1)
            {
                if (args[0] == "/?")
                {
                    DisplayUsage();
                }

                else
                {
                    Console.WriteLine("Error: Invalid argument (" + args[1] + ").");
                    DisplayUsage();
                }
            } 
            #endregion

            #region Two or More Args - Export Notebook
            else if (args.Length >= 2)
            {
                bool result;
                
                XmlNode xnNotebook = null;
                string strExportTgt = "";

                #region Verify notebook exists
                foreach (XmlNode n in xnlNotebooks)
                {
                    if (n.Attributes["name"].Value.ToLower() == args[0].ToLower())
                    {
                        xnNotebook = n;
                    }
                }
                if (xnNotebook == null)
                {
                    Console.WriteLine("Error: The specified notebook (" + args[0] + ") does not exist.");
                    return;
                }
                #endregion

                #region Verify location parameter
                
                string file = args[1].ToLower();

                // check file extension
                if ((file.Trim().ToLower()).EndsWith(".htm") |
                    (file.Trim().ToLower()).EndsWith(".html"))
                {
                    // Everything OK
                }
                else
                {
                    // add extension
                    file += ".htm";
                }

                // check directory existence
                if (file.ToLower().Contains("http://") | file.ToLower().Contains("https://"))
                {
                    // NO CHECK FOR HTTP://
                    // TODO: add check for HTTP
                    strExportTgt = file;
                }
                else
                {
                    // check local/UNC paths
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);

                    if (fileInfo.Directory.Exists)
                    {
                        strExportTgt = file;
                    }
                    else
                    {
                        Console.WriteLine("Error: The specified export location (" + fileInfo.Directory.FullName + ") does not exist.");
                        return;
                    }
                }
                #endregion

                #region Logging Setup
                // three or more arguments
                if (args.Length >= 3)
                {
                    logger.SetTextLog(args[2]);
                }
                #endregion

                #region Export Notebook
                DateTime tStart = System.DateTime.Now;
                logger.AppendLog("********************************************************");
                logger.AppendLog("BEGIN EXPORT OPERATION");
                logger.AppendLog("Start time: " + tStart.ToString());
                logger.AppendLog("Notebook: " + xnNotebook.Attributes["name"].Value);
                logger.AppendLog("Location: " + strExportTgt);
                logger.AppendLog("********************************************************");

                // get the sections for the notebook
                XmlNodeList xnlSections = Webber.ONXmlRequestor.GetNodes(oneApp, xnNotebook.Attributes["ID"].Value, Onenote.HierarchyScope.hsSections, "//one:Section");
                XmlNode[] pxnSections = new XmlNode[xnlSections.Count];
                for (int i = 0; i < xnlSections.Count; i++)
                {
                    pxnSections[i] = xnlSections.Item(i);
                }

                Webber.ONWebExport exporter = new Webber.ONWebExport(xnNotebook, pxnSections, strExportTgt, logger);
                result = exporter.ExportNotebook();

                DateTime tEnd = DateTime.Now;
                TimeSpan duration = tEnd - tStart;
                logger.AppendLog("********************************************************");
                logger.AppendLog("END EXPORT OPERATION");
                logger.AppendLog("Status: " + (result?"SUCCEEDED":"FAILED"));
                logger.AppendLog("End time: " + tEnd.ToString());
                logger.AppendLog("Duration: " + duration.ToString());
                logger.AppendLog("********************************************************");
                logger.AppendLog("");
                
                #endregion

                #region Close Logging
                // close log file
                logger.CloseTextLog();
                #endregion

            }
            #endregion

        }

        static void DisplayUsage()
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("To export a notebook type: cwebber <notebook> <export path> [log file]");
            Console.WriteLine();
            Console.WriteLine("- To list available notebooks type: cwebber");
            Console.WriteLine("- <notebook> should be quoted (eg. \"OneNote Guide\") and is not case sensitive");
            Console.WriteLine("- <export path> can be a filepath (absolute or relative) or an url (eg. http://mysharepointsite/doclib)");
            Console.WriteLine("- If the log file doesn't exist, it will be created. Otherwise the export will append to the existing file");
        }
     }
}
